// routes/user.js
const express = require('express');
const BookModel = require('../models/bookModel');
const authMiddleware = require('../middleware/authMiddleware');
const paginationService = require('../service/paginationService');
const path = require('path');
const XLSX = require('xlsx');
// 定义模板格式
const templateKeys = [
    {
        key: 'name',
        str: '第一列是名字',
    },
    {
        key: 'describe',
        str: '第二列是描述',
    },
    {
        key: 'type',
        str: '第三列是类型',
    },
];
module.exports = (db) => {
    const router = express.Router();

    // 获取分页列表
    router.post('/page', authMiddleware, async (req, res) => {
        // 假设用户信息已存储在 JWT payload 中
        const { page, limit, queryParams } = req.body;
        const paginationServiceController = new paginationService(db, 'books')
        try {
            const res1 = await paginationServiceController.paginate(page, limit, queryParams)
            res.json({
                code: 200,
                success: true,
                data: res1
            });
        } catch (err) {
            console.log('err--', err);

            return res.status(404).json({
                code: 404,
                success: false,
                message: 'Request fail',
            });
        }
        // db.query('SELECT * FROM users WHERE id = ?', [userId], (err, results) => {
        //     if (err || results.length === 0) {
        //         return res.status(404).json({
        //             code: 404,
        //             success: false,
        //             message: 'User not found',
        //         });
        //     }
        //     res.json({
        //         code: 200,
        //         success: true,
        //         data: results[0],
        //     });
        // });
    });


    // 批量导入
    router.post('/import', authMiddleware, async (req, res) => {
        try {
            console.log('req.body-----', req.body);
            const filePath = path.join(__dirname, req.body.path);

            const workbook = XLSX.readFile(filePath);
            const sheetName = workbook.SheetNames[0]; // 读取第一个工作表
            const worksheet = workbook.Sheets[sheetName];

            // 解析 Excel 数据
            const jsonData = XLSX.utils.sheet_to_json(worksheet);
            const errors = [];
            console.log('jsonData--', jsonData);

            // 验证每一行数据
            jsonData.forEach((row, index) => {
                const rowErrors = [];
                let str = ''
                templateKeys.forEach(res => {
                    if (!row[res.key]) {
                        // rowErrors.push({
                        //   row: `第 ${index + 1} 行`,
                        //   message: `第 ${index + 1} 行缺少 "${res.key}" 字段`
                        // });
                        str += `${res.key};`
                    }
                });
                rowErrors.push({
                    index,
                    row: `第 ${index + 1} 行`,
                    message: `第 ${index + 1} 行缺少 "${str}" 字段`
                });

                if (rowErrors.length > 0) {
                    errors.push(...rowErrors);
                }
            });
           let importData = jsonData.filter((item,index) => {
                return errors.every(ele => ele.index != index)
            })
            if(importData){
                Promise.all(importData.map(async (item) => {
                    return BookModel.createBook(item[templateKeys[0].key],item[templateKeys[1].key],item[templateKeys[2].key])
                })).then(res => {
                     console.log('res----');
                     
                })
            }

            // 根据错误返回响应
            if (errors.length > 0) {


                res.json({ code: 400, message: '模板格式有问题', data: errors });
            }

            // 处理有效数据（如果没有错误）
            // 这里可以处理有效数据，例如存储到数据库
            res.json({ code: 200, message: '文件上传成功', data: jsonData });
        } catch (err) {
            console.log('err', err);

        }
    });

    return router;
};